package com.zzy.chapter4.service;

import com.zzy.chapter4.facade.PayFacade;
import com.zzy.chapter4.pojo.Order;
import com.zzy.chapter4.state.OrderState;
import com.zzy.chapter4.state.OrderStateChangeAction;
import com.zzy.chapter4.transaction.colleague.AbstractCustomer;
import com.zzy.chapter4.transaction.colleague.Buyer;
import com.zzy.chapter4.transaction.colleague.Payer;
import com.zzy.chapter4.transaction.mediator.Mediator;
import com.zzy.chapter4.utils.RedisCommonProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class OrderService implements IOrderService{
    @Autowired
    private StateMachine<OrderState, OrderStateChangeAction> stateMachine;

    @Autowired
    private StateMachinePersister<OrderState, OrderStateChangeAction, String> stateMachinePersister;

    @Autowired
    private PayFacade payFacade;

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;
    @Autowired
    private StateMachine orderStateMachine;

    @Autowired
    private Mediator mediator;

    @Override
    public Order createOrder(String productId) {
        // 1. 创建订单
        String orderId = "OID" + productId;
        // 2. 创建订单并保存到redis
        Order order = Order.builder()
                .orderId(orderId)
                .productId(productId)
                .orderState(OrderState.ORDER_WAIT_PAY)
                .build();
        // 3. 保存到redis
        redisCommonProcessor.set(orderId, order, 900);

        return order;
    }

    @Override
    public Order payOrder(String orderId) {
        // 1. 从redis中取出订单
        Order order = (Order) redisCommonProcessor.get("OID" + orderId);
        // 2. 订单信息
        Message message = MessageBuilder
                .withPayload(OrderStateChangeAction.PAY_ORDER)
                .setHeader("order", order)
                .build();
        // 3. 将Message传入状态机，执行订单状态转换
        return changeStateAction(message, order) ? order : null;
    }

    @Override
    public Order send(String orderId) {
        // 1. 从redis中取出订单
        Order order = (Order) redisCommonProcessor.get("OID" + orderId);
        // 2. 订单信息
        Message message = MessageBuilder
                .withPayload(OrderStateChangeAction.SEND_ORDER)
                .setHeader("order", order)
                .build();
        // 3. 将Message传入状态机，执行订单状态转换
        return changeStateAction(message, order) ? order : null;
    }

    @Override
    public Order receive(String orderId) {
        // 1. 从redis中取出订单
        Order order = (Order) redisCommonProcessor.get("OID" + orderId);
        // 2. 订单信息
        Message message = MessageBuilder
                .withPayload(OrderStateChangeAction.RECEIVE_ORDER)
                .setHeader("order", order)
                .build();
        // 3. 将Message传入状态机，执行订单状态转换
        return changeStateAction(message, order) ? order : null;
    }

    private boolean changeStateAction(Message message, Order order) {
        try {
            // 1. 启动状态机
            orderStateMachine.start();
            // 2. 读取状态机
            stateMachinePersister.restore(orderStateMachine, order.getOrderId() + "STATE");
            // 3. 发送事件
            boolean res = orderStateMachine.sendEvent(message);
            // 4. 更改完订单状态，持久化状态机
            stateMachinePersister.persist(orderStateMachine, order.getOrderId() + "STATE");
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            orderStateMachine.stop();
        }
        return false;
    }

    @Override
    public String getPayUrl(String orderId, Float price, Integer payType) {

        Order order = (Order) redisCommonProcessor.get(orderId);
        if (order != null) {
            order.setPrice(price);
            String payUrl = payFacade.pay(order, payType);
            return payUrl;
        }

        return null;
    }

    @Override
    public void friendPay(String sourceCustomer, String orderId, String targetCustomer, String payResult, String role) {
        Buyer buyer = new Buyer(orderId, sourceCustomer, mediator);
        Payer payer = new Payer(orderId, sourceCustomer, mediator);
        HashMap<String, AbstractCustomer> map = new HashMap<>();
        map.put("buyer", buyer);
        map.put("payer", payer);
        mediator.currentCustomerInstance.put(orderId, map);
        if("B".equals(role)) {
            buyer.messageTransfer(orderId, targetCustomer, payResult);
        } else if("P".equals(role)) {
            payer.messageTransfer(orderId, targetCustomer, payResult);
        }
    }


}
